const axios = require('axios')
const { Service } = require('ee-core');
const Log = require('ee-core/log');
const fs = require('fs'); 
const Conf = require('ee-core/config');
const path = require('path');
const FormData = require('form-data'); // 引入FormData模块
const cfg = Conf.getValue('platformApi');



/**
 * UploadService
 * @class
 */
class UploadService extends Service {

  constructor(ctx) {
    super(ctx);
  }

  
  /** 上传文件
   * @param {String} absolutePath 如 '/profile/2024/01/01/sss.png'
   * @param {String} deviceCode 设备编号如50001
   */
  uploadDeviceFile(absolutePath, deviceCode) {
	try{
		let uploadUrl = cfg.url + 'httpcommon/uploadFile';
		Log.info("上传地址:"+uploadUrl);      
        // 创建一个新的FormData对象
        const formData = new FormData();
        // 将要上传的图片文件添加到FormData中
        formData.append('file_data', fs.createReadStream(absolutePath));
        formData.append('useSameName', '0');
        formData.append('deviceCode', deviceCode);        
        // 发送POST请求并上传图片文件
        axios({
            method: 'post',
            url: uploadUrl, // 设置上传接口URL
            data: formData,
            headers: {
                ...formData.getHeaders() // 获取表单数据的头部信息
            }
        })
        .then(response => {
            console.log('图片上传成功！');
            console.log(response);
        })
        .catch(error => {
            Log.error('图片上传失败！');
            console.error(error);
        });
		
	}catch (err){
		Log.error("axios upload exception:"+err)
	}
  }

  
}

UploadService.toString = () => '[class UploadService]';
module.exports = UploadService;  
  
// module.exports = service
